package wzj.mybatisplusdemo.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import wzj.mybatisplusdemo.po.Creation;
import wzj.mybatisplusdemo.po.User;
import wzj.mybatisplusdemo.service.CreationService;
import wzj.mybatisplusdemo.web.dto.RespEntity;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/mycreation")
public class MyCreationController {

    @Autowired
    private CreationService creationService;

    @Value("${my.img_dir}")
    private String imgDir;

    // 获取当前用户的创作列表（分页）
    @GetMapping("/list")
    public RespEntity myList(
            @RequestAttribute("curUser") User curUser,
            @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", defaultValue = "10") int pageSize
            ,@RequestParam(value = "search", defaultValue = "")String search) {

        Page<Creation> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Creation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().like(!search.isEmpty(),Creation::getTitle, search)
                .or().like(!search.isEmpty(),Creation::getContent, search)
                .eq(Creation::getUserId, curUser.getId())
                .orderByDesc(Creation::getCreateTime)
                .orderByDesc(Creation::getCreateTime);

        creationService.page(page, queryWrapper);
        return new RespEntity("2000", "查询成功", page);
    }

    // 获取创作详情（用于编辑）
    @GetMapping("/detail/{id}")
    public RespEntity detail(
            @RequestAttribute("curUser") User curUser,
            @PathVariable("id") Integer id) {

        Creation creation = creationService.getById(id);

        // 验证权限：只能查看自己的创作
        if (creation == null || creation.getUserId() != curUser.getId()) {
            return new RespEntity("4001", "无权限访问或资源不存在",null);
        }

        return new RespEntity("2000", "获取成功", creation);
    }

    // 更新创作信息
    @PostMapping("/update/{id}")
    public RespEntity update(
            @RequestAttribute("curUser") User curUser,
            @PathVariable("id") Integer id,
            Creation creation, // 使用@ModelAttribute接收表单数据
            @RequestParam(value = "pic", required = false) MultipartFile pic,
            @RequestParam(value = "ai_img_url", required = false) String ai_img_url) throws IOException {

        // 验证权限：只能更新自己的创作
        Creation existingCreation = creationService.getById(id);
        if (existingCreation == null || existingCreation.getUserId() != curUser.getId()) {
            return new RespEntity("4001", "无权限操作",null);
        }

        String dir = this.imgDir;
        File dirFile = new File(dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        // 处理图片更新
        if (ai_img_url != null && !ai_img_url.isEmpty()) {
            String fileName = saveImageFromUrl(ai_img_url, dir);
            creation.setImg(fileName);
        } else if (pic != null && !pic.isEmpty()) {
            String fileName = new Date().getTime() + "_" + pic.getOriginalFilename();
            pic.transferTo(new File(dir + "\\" + fileName));
            creation.setImg(fileName);
        } else {
            // 如果没有新图片，保留原图片
            creation.setImg(existingCreation.getImg());
        }

        // 确保关键字段不被前端修改
        creation.setId(id);
        creation.setUserId(curUser.getId()); // 用户ID保持不变
        creation.setClick(existingCreation.getClick()); // 点击量保持不变
        creation.setCreateTime(existingCreation.getCreateTime()); // 创建时间保持不变
        creationService.updateById(creation);
        return new RespEntity("2000", "更新成功", creation);
    }

    // 删除单个创作
    @DeleteMapping("/delete/{id}")
    public RespEntity delete(
            @RequestAttribute("curUser") User curUser,
            @PathVariable("id") Integer id) {

        // 验证权限：只能删除自己的创作
        Creation creation = creationService.getById(id);
        if (creation == null || creation.getUserId() != curUser.getId()) {
            return new RespEntity("4001", "无权限操作",null);
        }

        creationService.removeById(id);
        return new RespEntity("2000", "删除成功",null);
    }

    // 批量删除创作
    @PostMapping("/delete/batch")
    public RespEntity batchDelete(
            @RequestAttribute("curUser") User curUser,
            @RequestBody List<Integer> ids) {

        // 验证权限：只能删除自己的创作
        QueryWrapper<Creation> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .in(Creation::getId, ids)
                .eq(Creation::getUserId, curUser.getId());

        long validCount = creationService.count(queryWrapper);
        if (validCount != ids.size()) {
            return new RespEntity("4001", "包含无权限操作的资源",null);
        }

        creationService.removeByIds(ids);
        return new RespEntity("2000", "批量删除成功",null);
    }

    // 保存网络图片方法（从原有代码复制）
    public String saveImageFromUrl(String imageUrl, String dir) throws IOException {
        // 实现代码同原有方法
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(imageUrl);
        CloseableHttpResponse response = httpClient.execute(httpGet);

        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode >= 200 && statusCode < 300) {
                HttpEntity entity = response.getEntity();
                byte[] imageBytes = EntityUtils.toByteArray(entity);
                String fileName = new Date().getTime() + "_" + imageUrl.split("\\?")[0].substring(imageUrl.lastIndexOf("/") + 1);
                Path imagePath = Paths.get(dir, fileName);
                Files.write(imagePath, imageBytes);
                return fileName;
            }
            return null;
        } finally {
            response.close();
            httpClient.close();
        }
    }
}
